import 'dart:io';
import 'dart:ui';
import 'package:audio_metadata_reader/audio_metadata_reader.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animation/Utils/ColorUtil.dart';
import 'package:flutter_animation/More/widget/Music/Marquee.dart';
import 'package:flutter_lyric/lyric_ui/lyric_ui.dart';
import 'package:flutter_lyric/lyric_ui/ui_netease.dart';
import 'package:flutter_lyric/lyrics_model_builder.dart';
import 'package:flutter_lyric/lyrics_reader_model.dart';
import 'package:flutter_lyric/lyrics_reader_widget.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:path_provider/path_provider.dart';

import 'lyrics.dart';


class MusicPage extends StatefulWidget {
  const MusicPage({super.key});

  @override
  State<MusicPage> createState() => _MusicPageState();
}

class _MusicPageState extends State<MusicPage> {
  String title = '未知歌曲'; //曲名
  String artist = '未知歌手'; //歌手
  Uint8List backImage = Uint8List(0); //背景图片
  String songPath = ''; //歌曲本地路径
  File songFile = File(''); //歌曲文件
  late AudioMetadata metadata; //歌曲元数据
  AudioPlayer? audioPlayer;

  LyricsReaderModel lyricModel = LyricsReaderModel(); //歌词
  var lyricUI = UINetease();
  double sliderProgress  = 0.0; //进度
  int playProgress = 0; //进度
  double maxValue = 0.0; //总时长
  bool isTap = false;
  bool playing = false;


  @override
  void initState() {
    super.initState();
    getSongInfo();
  }

  getSongInfo() async {

    final dir = await getApplicationSupportDirectory();
    songPath = "${dir.path}/Sample.mp3";
    songFile = File(songPath);

    await loadLocalSong();
    // await downloadSong('https://xafj-cu11.baidupcs.com/file/90b86f64ak43693e8f709263f9eb8610?bkt=en-1df98aeb722e81f52e13d27bae90df9a9a92f5671f96f46a447f5cd9cd8aa7aff3d054d08f8d197d&fid=2945863547-250528-1001620357489080&time=1701682247&sign=FDTAXUbGERLQlBHSKfWqiu-DCb740ccc5511e5e8fedcff06b081203-4%2FpPaBK%2FOjyqLpoq7zZfeSd%2Fczs%3D&to=419&size=9069360&sta_dx=9069360&sta_cs=126&sta_ft=mp3&sta_ct=7&sta_mt=7&fm2=MH%2CXian%2CAnywhere%2C%2C%E6%B9%96%E5%8C%97%2Ccnc&ctime=1607271907&mtime=1607271907&resv0=-1&resv1=0&resv2=rlim&resv3=5&resv4=9069360&vuk=4130508660&iv=0&htype=&randtype=&tkbind_id=0&newver=1&newfm=1&secfm=1&flow_ver=3&pkey=en-b1ad5563709b414d50ad6799b9b06d2c80ccc4130813c3a98e0ffc36dad789df248e1d1f561e5f75&sl=76480590&expires=8h&rt=sh&r=155312279&vbdid=1476759599&fin=The+Chainsmokers+-+Paris.mp3&fn=The+Chainsmokers+-+Paris.mp3&rtype=1&clienttype=0&dp-logid=8985826973682664367&dp-callid=0.1&hps=1&tsl=80&csl=80&fsl=-1&csign=IOKafY4ZD%2BNy%2B44ebJ4bbRJpvVs%3D&so=0&ut=6&uter=4&serv=0&uc=1868481949&ti=068bcab50ae430c7ce729c8fc3a4f3ffdeb98598d6e3bb4c&hflag=30&from_type=1&adg=c_b5c3d97a06981db2af16750efcb5df62&reqlabel=250528_f_23799e41db2598b542b1dda64ab8a397_-1_b9d19ac78d4153f9501184e6b5174ee0&fpath=2020%2Flinks%2F12&by=themis&resvsflag=1-0-0-1-1-1');
    
    metadata = readMetadata(songFile, getImage: true);

    if (metadata.lyrics != null) {
      lyricModel = LyricsModelBuilder.create()
      .bindLyricToMain(metadata.lyrics!)
      .getModel();
    } else {
      lyricModel = LyricsModelBuilder.create()
      .bindLyricToMain(normalLyric)
      .bindLyricToExt(transLyric)
      .getModel();
    }
    
    
    setState(() {
      backImage = metadata.pictures[0].bytes;
      title = metadata.title ?? '未知歌曲';
      artist = metadata.artist ?? '未知歌手';
    });

    audioPlayer?.onPositionChanged.listen((Duration event) {
      setState(() {
        sliderProgress = event.inMilliseconds.toDouble();
        playProgress = event.inMilliseconds;
      });
    });
  }

  // 读取本地asset歌曲
  loadLocalSong() async {
    var bytes = await rootBundle.load("assets/songs/The Chainsmokers - Paris.mp3");
    final buffer = bytes.buffer;
    await songFile.writeAsBytes(buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
  }

  // 下载歌曲，用于读取背景图、歌名、歌手
  downloadSong(String url) async {
    try {
      await Dio().download(
        url,
        songPath,
        onReceiveProgress: (int count, int total) {
          if (total != -1) {
            if (mounted) {
              setState(() {
                // pages = 0;
                // progress = count / total;
              });
            }
            if (count == total) {
              if (mounted) {
                setState(() {
                  // pages = 1;
                });
              }
            }
          } else {
            SmartDialog.showToast('无法获取文件大小，下载失败',displayType: SmartToastType.last);
          }
        },
      );
    } catch (e) {
      SmartDialog.showToast('文件下载失败',displayType: SmartToastType.last);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Music"),
      ),
      body: Stack(
        children: [
          backImage.isNotEmpty ?
          Image.memory(
            backImage,
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ) :
          Image.asset(
            'assets/images/post_malone.png',
            color: Colors.black,
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),
          BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 50, sigmaY: 50),
            child: Container(
              color: Colors.transparent,
            ),
          ),
          SingleChildScrollView(
            child: Column(
              children: [
                SizedBox(height: MediaQuery.of(context).padding.top),
                buildBar(),
                buildImage(),
                buildInfo(),
                buildLyric(),
                buildController(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  buildBar() {
    return Row(
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            SmartDialog.showToast('点击关闭',displayType: SmartToastType.last);
          },
          child: Padding(
            padding: const EdgeInsets.only(left: 15,right: 15,top: 15),
            child: Image.asset(
              'assets/images/down_arrow.png',
              height: 24,
              width: 24,
            ),
          ),
        ),
        Expanded(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  SmartDialog.showToast('点击推荐',displayType: SmartToastType.last);
                },
                child: const Padding(
                  padding: EdgeInsets.only(left: 12,right: 12,top: 15),
                  child: Text(
                    '推荐',
                    style: TextStyle(
                      fontSize: 15,
                      color: ColorUtil.color999999_50,
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 15),
                child: Container(
                  width: 0.25,
                  height: 8,
                  color: Colors.white,
                ),
              ),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  SmartDialog.showToast('点击歌曲',displayType: SmartToastType.last);
                },
                child: const Padding(
                  padding: EdgeInsets.only(left: 12,right: 12,top: 15),
                  child: Text(
                    '歌曲',
                    style: TextStyle(
                      fontSize: 15,
                      color: ColorUtil.color999999_50,
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 15),
                child: Container(
                  width: 0.25,
                  height: 8,
                  color: Colors.white,
                ),
              ),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  SmartDialog.showToast('点击歌词',displayType: SmartToastType.last);
                },
                child: const Padding(
                  padding: EdgeInsets.only(left: 12,right: 12,top: 15),
                  child: Text(
                    '歌词',
                    style: TextStyle(
                      fontSize: 15,
                      color: ColorUtil.color999999_50,
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            SmartDialog.showToast('点击分享',displayType: SmartToastType.last);
          },
          child: Padding(
            padding: const EdgeInsets.only(left: 15,right: 15,top: 15),
            child: Image.asset(
              'assets/images/share.png',
              height: 24,
              width: 24,
            ),
          ),
        ),
      ],
    );
  }

  buildImage() {
    return Padding(
      padding: const EdgeInsets.all(30),
      child: Container(
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(30),
        ),
        child: backImage.isNotEmpty ?
        Image.memory(
          backImage,
          fit: BoxFit.cover,
          width: double.infinity,
        ) :
        Image.asset(
          'assets/images/default_back_image.png',
          fit: BoxFit.cover,
          width: double.infinity,
        ),
      ),
    );
  }

  bool like = false;
  bool scrollFlag = false;
  int scrollCount = 1;
  buildInfo() {
    return Row(
      children: [
        const SizedBox(width: 30),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Marquee(
                title,
                textStyle: const TextStyle(
                  fontSize: 24,
                  color: ColorUtil.colorWhite,
                ),
                scrollDuration: const Duration(milliseconds: 50),
              ),
              const SizedBox(height: 12),
              Marquee(
                artist,
                textStyle: const TextStyle(
                  fontSize: 14,
                  color: ColorUtil.color999999_50,
                ),
                scrollDuration: const Duration(milliseconds: 50),
              ),
            ],
          ),
        ),
        const SizedBox(width: 12),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            setState(() {
              like = !like;
            });
          },
          child: Image.asset(
            like ? 'assets/images/ic_music_like_active.png' : 'assets/images/ic_music_like.png',
            width: 30,
            height: 30,
          ),
        ),
        const SizedBox(width: 30),
      ],
    );
  }

  buildLyric() {
    lyricUI.lyricAlign = LyricAlign.LEFT;

    return LyricsReader(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      model: lyricModel,
      position: playProgress,
      lyricUi: lyricUI,
      playing: playing,
      size: const Size(double.infinity, 35),
      emptyBuilder: () => Center(
        child: Text(
          "暂无歌词",
          style: lyricUI.getOtherMainTextStyle(),
        ),
      ),
      selectLineBuilder: (progress, confirm) {
        return Row(
          children: [
            IconButton(
              onPressed: () {
                confirm.call();
                setState(() {
                  audioPlayer?.seek(Duration(milliseconds: progress));
                });
              },
              icon: const Icon(Icons.play_arrow, color: ColorUtil.color999999),
            ),
          ],
        );
      },
    );
  }

  buildController() {
    return Column(
      children: [
        Slider(
          min: 0,
          max: maxValue,
          label: sliderProgress.toString(),
          value: sliderProgress,
          activeColor: Colors.white54,
          inactiveColor: Colors.white,
          onChanged: (double value) {
            setState(() {
              sliderProgress = value;
            });
          },
          onChangeStart: (double value) {
            isTap = true;
          },
          onChangeEnd: (double value) {
            isTap = false;
            setState(() {
              playProgress = value.toInt();
            });
            audioPlayer?.seek(Duration(milliseconds: value.toInt()));
          },
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: () async {
                if (audioPlayer == null) {
                  audioPlayer = AudioPlayer()..play(AssetSource('songs/The Chainsmokers - Paris.mp3'));
                  setState(() {
                    playing = true;
                  });
                  audioPlayer?.onDurationChanged.listen((Duration event) {
                    setState(() {
                      maxValue = event.inMilliseconds.toDouble();
                    });
                  });
                  audioPlayer?.onPositionChanged.listen((Duration event) {
                    if (isTap) return;
                    setState(() {
                      sliderProgress = event.inMilliseconds.toDouble();
                      playProgress = event.inMilliseconds;
                    });
                  });

                  audioPlayer?.onPlayerStateChanged.listen((PlayerState state) {
                    setState(() {
                      playing = state == PlayerState.playing;
                    });
                  });
                } else {
                  playing ? audioPlayer?.pause() : audioPlayer?.resume();
                }
              },
              child: Image.asset(
                playing ? 'assets/images/resume.png' : 'assets/images/play.png',
                width: 50,
                height: 50,
              ),
            ),
            Container(
              width: 10,
            ),
            TextButton(
                onPressed: () async {
                  audioPlayer?.stop();
                  audioPlayer = null;
                },
                child: const Text("停止")),
          ],
        )
      ],
    );
  }
}
